
package com.ceair.mub2c.payment.payments.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.ceair.flight.booking.service.IPromotionService;
import com.ceair.flight.enums.OrderTypeEnum;
import com.ceair.flight.enums.PayPCEnum;
import com.ceair.flight.enums.PayPOINTEnum;
import com.ceair.flight.enums.PaySCEnum;
import com.ceair.flight.enums.PaySUBPCEnum;
import com.ceair.flight.enums.PaySUBSCEnum;
import com.ceair.flight.enums.ProductTypeEnum;
import com.ceair.flight.logging.core.KafkaLayout;
import com.ceair.flight.logging.enums.Source;
import com.ceair.flight.payment.dto.CardInfoDto;
import com.ceair.flight.payment.dto.PayResponseDto;
import com.ceair.flight.payment.dto.PayTypeRq;
import com.ceair.flight.payment.dto.SyncPaymentCallbackDto;
import com.ceair.flight.po.model.OrderDO;
import com.ceair.flight.po.model.PayDO;
import com.ceair.flight.po.model.PromotionDO;
import com.ceair.flight.query.dto.FlightOrderDto;
import com.ceair.flight.query.dto.OrderDto;
import com.ceair.flight.query.dto.PaxDto;
import com.ceair.flight.query.dto.PayProductDto;
import com.ceair.flight.query.dto.SegmentDto;
import com.ceair.flight.query.emd.service.IEmdOrderService;
import com.ceair.flight.query.flightorder.dto.FlightOrderReq;
import com.ceair.flight.query.newOrder.dto.BookingOrderDto;
import com.ceair.flight.query.newOrder.dto.SeatDto;
import com.ceair.flight.query.newOrder.param.BookingOrderMoreParam;
import com.ceair.flight.query.newOrder.param.SeatParam;
import com.ceair.flight.query.payment.service.IPayQueryService;
import com.ceair.flight.query.service.IFlightOrderService;
import com.ceair.flight.query.service.IOrderService;
import com.ceair.mub2c.common.user.UserContext;
import com.ceair.mub2c.common.utils.GlobalExceptionConstants;
import com.ceair.mub2c.common.utils.GlobalExceptionUtils;
import com.ceair.mub2c.common.utils.HttpUtils;
import com.ceair.mub2c.exceptionhandler.ActionException;
import com.ceair.mub2c.exceptionhandler.BaseExceptionController;
import com.ceair.mub2c.payment.payments.service.CeairWalletService;
import com.ceair.mub2c.payment.payments.service.PaymentService;
import com.ceair.mub2c.payment.payments.utils.XmlToDtoUtils;
import com.ceair.mub2c.payment.payments.vo.PayStatusVO;
import com.ceair.mub2c.payment.payments.vo.PaymentRes;
import com.ceair.mub2c.payment.payments.vo.PaymentVO;
import com.ceair.mub2c.payment.payments.vo.WalletAcquireReq;
import com.ceair.mub2c.payment.payments.vo.WalletAcquireRes;
import com.ceair.mub2c.payment.payments.vo.WalleterDto;
import com.ceair.unified.businessobject.base.BaseRS;
import com.ceair.unified.businessobject.rqrs.unicfg.UniConfigRS;
import com.ceair.unified.businessobject.rqrs.unicfg.UniFndConfigRS;
import com.ceair.unified.businessobject.rqrs.unicfg.UniPayRS;
import com.ceair.unified.ws.unicfgmanager.IUniConfigManagerWS;

@Source(name = "10031001")
@Controller
@RequestMapping(value = "/payment")
public class PaymentController extends BaseExceptionController {

//	private static final Log logger = LogFactory.getLog(PaymentController.class);
    @Autowired
    private PaymentService paymentService;

    @Autowired
    private IPayQueryService payQueryService;

    @Autowired
    private IUniConfigManagerWS uniConfigManagerWS;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IFlightOrderService flightOrderService;

    @Autowired
    private IPromotionService promotionService;
    
    @Autowired
    private IEmdOrderService emdOrderService;
    
    @Autowired
    private CeairWalletService ceairWalletService;

    //private static final String ZERO = "0";

    Logger log = Logger.getLogger(getClass());

    @Source(name = "100310011001")
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    @ResponseBody
    public PaymentRes paymentSubmit(HttpServletRequest request, @RequestBody CardInfoDto cardInfo, @RequestParam String productTypes, @RequestParam String orderNo, @RequestParam Integer payType, @RequestParam(required = false) String bankCode, @RequestParam(required = false) String accountId, @RequestParam(required = false) String accountPwd, @RequestParam BigDecimal amount,
            @RequestParam String SCCode, @RequestParam String SubSCCode, @RequestParam String PCCode, @RequestParam String SubPCCode, @RequestParam String PCCodePoint, @RequestParam String SubPCCodePoint, @RequestParam(required = false) BigDecimal pointAmount, @RequestParam(required = false) String productIds, @RequestParam(required = false) String bookingOrderNo,@RequestParam(required = false) String walletPwd) {
        try {
            PaymentRes res = new PaymentRes();
            String[] split = productTypes.split(",");
            boolean flag = false;
            for (String string : split) {
                if ("1".equals(string)) {
                    flag = true;
                    break;
                }
            }
            //机票订单支付
            OrderDto orderDetail = orderService.getOrderDetail(orderNo);
            List<FlightOrderDto> flightOrders = orderDetail.getFlightOrders();
            if (flag) {
                //判断是否重要航班，决定是否进行验舱验价
                if (flightOrders != null && flightOrders.size() > 0) {
                    FlightOrderDto flightOrderDto = flightOrders.get(0);//默认是都只是新建订单，飞机订单一条
                    //支付之前的同人重复订单校验，考虑新建订单，没有考虑改期
                    res = checkRepetitionOrder(flightOrderDto);
                    if (!StringUtils.isEmpty(res.getCode())) {
                        return res;
                    }
                    if ("Y".equals(flightOrderDto.getIsImportantFlight())) {
                        //支付之前的验舱验价操作
                        boolean validateFlight = paymentService.validateFlight(flightOrderDto);
                        if (!validateFlight) {
                            log.info("支付之前验舱验价------仓位已无法预定");
                            throw new ActionException(GlobalExceptionConstants.PAYMENT_00010);
                        }
                    }
                }
                FlightOrderDto flightOrderDto = flightOrders.get(0);
                log.info("支付前校验促销码可用状态");
                if (null != flightOrderDto && !StringUtils.isEmpty(flightOrderDto.getPromoCode())) {
                	if(!StringUtils.isEmpty(flightOrderDto.getPromoTp()) && "2".equalsIgnoreCase(flightOrderDto.getPromoTp())){
                		
                	}else{
	                    Map<String, Object> param = new HashMap<String, Object>();
	                    int length = flightOrderDto.getSite().length();
	                    param.put("promoCode", flightOrderDto.getPromoCode());
	                    param.put("site", flightOrderDto.getSite().substring(length-2));
	                    log.info("查询当前站点下促销码集合");
	                    List<PromotionDO> promotionDOList = promotionService.getPromotionByPromoCodeAndSiteAndChlCode(param);
	                    
	                    boolean validatePromotionFlag = false;
	                    
	                    if(CollectionUtils.isNotEmpty(promotionDOList)){
	                    	log.info("校验促销码集合是否存在可用的");
	                    	validatePromotionFlag = paymentService.validatePromotion(promotionDOList,param,flightOrderDto);
	                    	if(!validatePromotionFlag){
	                    		throw getNoPromoMsg(flightOrderDto);
	                    	}
	                    } else {
	                    	log.info("查询当前站点下促销码集合为空");
	                        throw getNoPromoMsg(flightOrderDto);
	                    }
                	}
                }
            }

            String[] productIdArray = StringUtils.isEmpty(productIds) ? null : productIds.split(",");
            String[] productTypesArray = StringUtils.isEmpty(productTypes) ? null : productTypes.split(",");
            String clientIps = HttpUtils.getIpAddr(request);
            String sessionUserId = UserContext.getUser(request) == null ? "guest" : UserContext.getUser(request).getCustomerid();
            String sessionUserName = UserContext.getUser(request) == null ? "guest" : UserContext.getUser(request).getFullname();
            OrderDO orderDO = orderService.getOrderDoDetail(orderNo);
            String site = orderDO.getSite();
            log.info(KafkaLayout.format(orderNo, null, sessionUserId, sessionUserName, clientIps, "支付开始，开始时间：" + System.currentTimeMillis()));
            /*生产配置******************************************************************/
            StringBuffer url = request.getRequestURL();
            log.info("支付回调地址1：------------" + url + "-----------------");
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/mub2c").append(request.getServletContext().getContextPath()).append("/").toString();
            log.info("支付回调地址2：------------" + tempContextUrl + "-----------------");
            String asyncUrl = tempContextUrl + "payment/async";
            String syncUrl = tempContextUrl + "payment/sync/" + site;

            if (tempContextUrl.indexOf("test") > 0) {
                /*测试配置******************************************************************/
                asyncUrl = "http://10.18.18.179:8080/portal/payment/async";
                syncUrl = "http://10.18.18.179:8080/portal/payment/sync/" + site;
            }
            if (tempContextUrl.indexOf("dev") > 0) {
                /*开发配置*****************************************************************/
                asyncUrl = "http://172.31.69.157:8080/portal/payment/async";
                syncUrl = "http://172.31.69.157:8080/portal/payment/sync/" + site;
            }
            //统一支付异步回调地址切换https站点的配置
            String asyncUrlSite = uniConfigManagerWS.findSiteInfo2ByChannel(111111L).getUniconfigVO().getAsyncUrlSite();
            if(StringUtils.isNotEmpty(asyncUrlSite) && asyncUrlSite.contains(site)){
            	asyncUrl = asyncUrl.replace("http","https");
            	syncUrl = syncUrl.replace("http","https");
            }

            //加密校验消费密码
            WalletAcquireRes walletRandomAcquireRes = new WalletAcquireRes();
            String userId = null;
        	if (walletPwd != null && !"".equals(walletPwd)) {
        		log.info("订单号" +orderNo +"钱包支付");
        		//请求流水号:UUID 
        		String reqId = UUID.randomUUID().toString().toLowerCase();
        		//用户信息查询
        		WalletAcquireReq walleterReq = new WalletAcquireReq(SCCode, SubSCCode, reqId, null, accountId, "mufly", "ceair", "1");
        		WalleterDto walleter = ceairWalletService.getUserInfo(walleterReq);
        		userId = walleter.getUserId();
        		log.info("通过常客号" +sessionUserId +"查询钱包号"+ userId +"用于钱包积分支付");
        		WalletAcquireReq walletRandomReq = new WalletAcquireReq(SCCode, SubSCCode, reqId, userId, accountId, "mufly", "ceair", "1");
    			walletRandomAcquireRes = ceairWalletService.getWalletRandomAcquire(walletRandomReq);
    			if (!"success".equals(walletRandomAcquireRes.getResultCode())) {
    				log.info("钱包积分支付获取随机数失败");
    				res.setCode(walletRandomAcquireRes.getResultMsg());
    				return res;
				}
    		}
            String accountInfo = null;
            
            if (UserContext.getUser(request) != null && StringUtils.isNotEmpty(UserContext.getUser(request).getFfpno()) && StringUtils.isNotEmpty(walletPwd)) {
				String randJnlNo = walletRandomAcquireRes.getRandJnlNo();//随机流水号
				String random = walletRandomAcquireRes.getRandom();//随机数
				String ffpno = UserContext.getUser(request).getFfpno();//积分账号
				//积分账号|钱包积分密码|密码随机数流水号|密码随机数|钱包号
				accountInfo = ffpno + "|" + walletPwd + "|" + randJnlNo + "|" + random + "|" + userId;
			} else if (StringUtils.isNotEmpty(accountId) && StringUtils.isNotEmpty(accountPwd)) {
                accountInfo = accountId + "|" + accountPwd;
            }else  if (UserContext.getUser(request) != null && StringUtils.isNotEmpty(UserContext.getUser(request).getFfpno()) && StringUtils.isNotEmpty(accountPwd)) {
                accountInfo = UserContext.getUser(request).getFfpno() + "|" + accountPwd;
            }

//            try {
//                log.info("保存常用卡信息：" + cardInfo.isSaveFlag() + "|" + accountId);
//                if (StringUtils.isNotEmpty(accountId) && cardInfo.isSaveFlag() == true) {
//                    cardInfo.setCeairMember(accountId);
//                    CommonCardInfoRespDto commonCardInfoRespDto = paymentService.insertCard(SCCode, SubSCCode, PCCode, SubPCCode, cardInfo);
//                    if ("00".equals(commonCardInfoRespDto.getRspCode())) {
//                        log.info("保存常用卡信息成功");
//                    }
//                } else if (StringUtils.isNotEmpty(accountId) && cardInfo.isSaveFlag() == false) {
//                    cardInfo.setCeairMember(accountId);
//                    CommonCardInfoRespDto commonCardInfoRespDto = paymentService.deleteCard(SCCode, SubSCCode, cardInfo);
//                    if ("00".equals(commonCardInfoRespDto.getRspCode())) {
//                        log.info("删除常用卡信息成功");
//                    }
//                }
//            } catch (Exception e) {
//                log.error("保存常用卡信息错误", e);
//            }

            log.info("支付回调地址3：------------" + asyncUrl + "-----------------");
            log.info("支付回调地址3：------------" + syncUrl + "-----------------");
            String jsessionid = request.getSession().getId();
            log.info("提交支付请求：orderNo=" + orderNo + "------------jsessionid=" + jsessionid);
            
            PaymentVO paymentVO = paymentService.paymentSubmit(jsessionid, sessionUserId, sessionUserName, productTypesArray, orderNo, productIdArray, payType, bankCode, accountInfo, amount, pointAmount, clientIps, site, cardInfo, SCCode, SubSCCode, PCCode, SubPCCode, PCCodePoint, SubPCCodePoint, asyncUrl, syncUrl, bookingOrderNo);
            log.info(KafkaLayout.format(orderNo, null, sessionUserId, sessionUserName, clientIps, "支付开始，开始时间：" + System.currentTimeMillis()));
            res.setPaymentVO(paymentVO);
            res.setCode("10000");
            return res;
        } catch (Exception e) {
            log.error("支付提交异常" + orderNo, e);
        }
        return null;
    }
    
    @Source(name = "100310011021")
    @RequestMapping(value = "/paySubmit", method = RequestMethod.POST)
    @ResponseBody
    public PaymentRes paySubmit(HttpServletRequest request, @RequestBody CardInfoDto cardInfo, 
    			@RequestParam String orderNo, @RequestParam Integer payType,
    			@RequestParam(required = false) String bankCode, 
    			@RequestParam(required = false) String accountId, @RequestParam(required = false) String accountPwd, 
    			@RequestParam BigDecimal amount, @RequestParam(required = false) BigDecimal pointAmount,
    			@RequestParam String payMethod,
    			@RequestParam String bookingOrderNo) {
        try {
        		BookingOrderMoreParam bookingOrderMoreParam = new BookingOrderMoreParam();
        		bookingOrderMoreParam.setBookingOrderNo(bookingOrderNo);
			List<BookingOrderDto> bookingOrderDtoList = flightOrderService.getBookingOrderDtoListByMoreParam(bookingOrderMoreParam);
			if (null == bookingOrderDtoList || bookingOrderDtoList.size() == 0) {
				throw new ActionException(GlobalExceptionConstants.ORDER_000002);
			}
			String productIds = "";
			String productTypes = "";
			String productInfo = "MAIN";
			BookingOrderDto bookingOrderDto = bookingOrderDtoList.get(0);
			FlightOrderDto flightInfoDto = null;
			if (null != bookingOrderDto.getFlightOrderNo()) {
				OrderDto orderDetail = orderService.getOrderDetail(orderNo);
				List<FlightOrderDto> flightOrders = orderDetail.getFlightOrders();
				for(int i = 0;null!=flightOrders&&i<flightOrders.size();i++) {
					if(bookingOrderDto.getFlightOrderNo().equals(flightOrders.get(i).getFlightOrderNo())) {
						flightInfoDto = flightOrders.get(i);
					}
				}
				if (OrderTypeEnum.ORIGINAL_ORDER.getCode().equals(flightInfoDto.getOrderTp())) {
					log.info("提交机票订单支付：" + bookingOrderDto.getFlightOrderNo());
					productIds = bookingOrderDto.getFlightOrderNo() + ",";
					productTypes = ProductTypeEnum.FLIGHTORDER.getCode() + ",";
				} else if (OrderTypeEnum.RESCHEDULE_ORDER.getCode().equals(flightInfoDto.getOrderTp())) {
					log.info("提交机票改期订单支付：" + bookingOrderDto.getFlightOrderNo());
					productIds = bookingOrderDto.getFlightOrderNo() + ",";
					productTypes = ProductTypeEnum.RESCHEDULE.getCode() + ",";
				} else if (OrderTypeEnum.UPDATED_ORDER.getCode().equals(flightInfoDto.getOrderTp())) {
					log.info("提交机票升舱订单支付：" + bookingOrderDto.getFlightOrderNo());
					productIds = bookingOrderDto.getFlightOrderNo() + ",";
					productTypes = ProductTypeEnum.UPGRADE.getCode() + ",";
					productInfo = "UPGRADECLASS";
				}
			} 
			if (null != bookingOrderDto.getSeatOrderNo()) {
				log.info("提交选座订单支付：" + bookingOrderDto.getSeatOrderNo());
				productIds = bookingOrderDto.getSeatOrderNo() + ",";
				productTypes = ProductTypeEnum.EMD.getCode() + ",";
				if(null == bookingOrderDto.getFlightOrderNo()) {
					productInfo = "EMD";
				}
			} 
			if (null != bookingOrderDto.getBageOrderNo()) {
				log.info("提交行李订单支付：" + bookingOrderDto.getBageOrderNo());
				productIds = bookingOrderDto.getBageOrderNo() + ",";
				productTypes = ProductTypeEnum.BAGGAGE.getCode() + ",";
				if(null == bookingOrderDto.getFlightOrderNo()) {
					productInfo = "BAGGAGE";
				}
			} 
			if (null != bookingOrderDto.getGaotieOrderNo()) {
				log.info("提交高铁订单支付：" + bookingOrderDto.getGaotieOrderNo());
				productIds = bookingOrderDto.getGaotieOrderNo() + ",";
				productTypes = ProductTypeEnum.GAOTIE.getCode() + ",";
			} 
			if (null != bookingOrderDto.getPurchasePointOrderNo()) {
				log.info("提交积分订单支付：" + bookingOrderDto.getPurchasePointOrderNo());
				productIds = bookingOrderDto.getPurchasePointOrderNo() + ",";
				productTypes = ProductTypeEnum.POINT.getCode() + ",";
				if(null == bookingOrderDto.getFlightOrderNo()) {
					productInfo = "POINTPURCHASE";
				}
			}
			if ("".equals(productIds)) {
				throw new ActionException(GlobalExceptionConstants.ORDER_000002);
			}
			productIds = productIds.substring(0, productIds.length() - 1);
			productTypes = productTypes.substring(0, productTypes.length() - 1);
            PaymentRes res = new PaymentRes();
            //机票订单支付
            if (null != flightInfoDto) {
                //判断是否重要航班，决定是否进行验舱验价                   
                //支付之前的同人重复订单校验，考虑新建订单，没有考虑改期
                res = checkRepetitionOrder(flightInfoDto);
                if (!StringUtils.isEmpty(res.getCode())) {
                    return res;
                }
                if ("Y".equals(flightInfoDto.getIsImportantFlight())) {
                    //支付之前的验舱验价操作
                    boolean validateFlight = paymentService.validateFlight(flightInfoDto);
                    if (!validateFlight) {
                        log.info("支付之前验舱验价------仓位已无法预定");
                        throw new ActionException(GlobalExceptionConstants.PAYMENT_00010);
                    }
                }              
                log.info("支付前校验促销码可用状态");
                if (null != flightInfoDto && !StringUtils.isEmpty(flightInfoDto.getPromoCode())) {
                		if(!StringUtils.isEmpty(flightInfoDto.getPromoTp()) && "2".equalsIgnoreCase(flightInfoDto.getPromoTp())){
                		
                		}else{
	                    Map<String, Object> param = new HashMap<String, Object>();
	                    int length = flightInfoDto.getSite().length();
	                    param.put("promoCode", flightInfoDto.getPromoCode());
	                    param.put("site", flightInfoDto.getSite().substring(length-2));
	                    log.info("查询当前站点下促销码集合");
	                    List<PromotionDO> promotionDOList = promotionService.getPromotionByPromoCodeAndSiteAndChlCode(param);
	                    
	                    boolean validatePromotionFlag = false;
	                    
	                    if(CollectionUtils.isNotEmpty(promotionDOList)){
	                    	log.info("校验促销码集合是否存在可用的");
	                    	validatePromotionFlag = paymentService.validatePromotion(promotionDOList,param,flightInfoDto);
	                    	if(!validatePromotionFlag){
	                    		throw getNoPromoMsg(flightInfoDto);
	                    	}
	                    } else {
	                    	log.info("查询当前站点下促销码集合为空");
	                        throw getNoPromoMsg(flightInfoDto);
	                    }
                		}
                }
            }

            String[] productIdArray = StringUtils.isEmpty(productIds) ? null : productIds.split(",");
            String[] productTypesArray = StringUtils.isEmpty(productTypes) ? null : productTypes.split(",");
            String clientIps = HttpUtils.getIpAddr(request);
            String sessionUserId = UserContext.getUser(request) == null ? "guest" : UserContext.getUser(request).getCustomerid();
            String sessionUserName = UserContext.getUser(request) == null ? "guest" : UserContext.getUser(request).getFullname();
            OrderDO orderDO = orderService.getOrderDoDetail(orderNo);
            String site = orderDO.getSite();
            log.info(KafkaLayout.format(orderNo, null, sessionUserId, sessionUserName, clientIps, "支付开始，开始时间：" + System.currentTimeMillis()));
            /*生产配置******************************************************************/
            StringBuffer url = request.getRequestURL();
            log.info("支付回调地址1：------------" + url + "-----------------");
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/mub2c").append(request.getServletContext().getContextPath()).append("/").toString();
            log.info("支付回调地址2：------------" + tempContextUrl + "-----------------");
            String asyncUrl = tempContextUrl + "payment/async";
            String syncUrl = tempContextUrl + "payment/sync/" + site;

            if (tempContextUrl.indexOf("test") > 0) {
                /*测试配置******************************************************************/
                asyncUrl = "http://10.18.18.179:8080/portal/payment/async";
                syncUrl = "http://10.18.18.179:8080/portal/payment/sync/" + site;
            }
            if (tempContextUrl.indexOf("dev") > 0) {
                /*开发配置*****************************************************************/
                asyncUrl = "http://172.31.69.157:8080/portal/payment/async";
                syncUrl = "http://172.31.69.157:8080/portal/payment/sync/" + site;
            }
            //统一支付异步回调地址切换https站点的配置
            String asyncUrlSite = uniConfigManagerWS.findSiteInfo2ByChannel(111111L).getUniconfigVO().getAsyncUrlSite();
            if(StringUtils.isNotEmpty(asyncUrlSite) && asyncUrlSite.contains(site)){
            	asyncUrl = asyncUrl.replace("http","https");
            	syncUrl = syncUrl.replace("http","https");
            }

            String accountInfo = null;
            if (StringUtils.isNotEmpty(accountId) && StringUtils.isNotEmpty(accountPwd)) {
                accountInfo = accountId + "|" + accountPwd;
            } else if (UserContext.getUser(request) != null && StringUtils.isNotEmpty(UserContext.getUser(request).getFfpno()) && StringUtils.isNotEmpty(accountPwd)) {
                accountInfo = UserContext.getUser(request).getFfpno() + "|" + accountPwd;
            }

            log.info("支付回调地址3：------------" + asyncUrl + "-----------------");
            log.info("支付回调地址3：------------" + syncUrl + "-----------------");
            String jsessionid = request.getSession().getId();
            log.info("提交支付请求：orderNo=" + orderNo + "------------jsessionid=" + jsessionid);
			if(null == payMethod || "".equals(payMethod)) {
				payMethod = "WORLDPAY";
			}
			String SCCode = PaySCEnum.getBySite(site);
			String SubSCCode = PaySUBSCEnum.getBySite(site);
			String PCCode = PayPCEnum.getByPayMethod(payMethod);
			String SubPCCode = PaySUBPCEnum.getByParam(site, productInfo,payMethod);
			String PCCodePoint = PayPOINTEnum.PCCODEPOINT.getCode();
			String SubPCCodePoint = PayPOINTEnum.getByParam(site, productInfo);
            PaymentVO paymentVO = paymentService.paymentSubmit(jsessionid, sessionUserId, sessionUserName, productTypesArray, orderNo, productIdArray, payType, bankCode, accountInfo, amount, pointAmount, clientIps, site, cardInfo, SCCode, SubSCCode, PCCode, SubPCCode, PCCodePoint, SubPCCodePoint, asyncUrl, syncUrl, bookingOrderNo);
            log.info(KafkaLayout.format(orderNo, null, sessionUserId, sessionUserName, clientIps, "支付开始，开始时间：" + System.currentTimeMillis()));
            res.setPaymentVO(paymentVO);
            res.setCode("10000");
            return res;
        } catch (Exception e) {
            log.error("支付提交异常" + orderNo, e);
        }
        return null;
    }

    private ActionException getNoPromoMsg(FlightOrderDto flightOrderDto) {
        if (StringUtils.isEmpty(flightOrderDto.getPointTp())) {
            log.info("普通订单：很抱歉！您的促销码已被使用。");
            return new ActionException(GlobalExceptionConstants.PAYMENT_00012);
        } else {
            log.info("普通订单：很抱歉！你的积分抵用券已被使用。");
            return new ActionException(GlobalExceptionConstants.PAYMENT_00013);
        }
    }

    private PaymentRes checkRepetitionOrder(FlightOrderDto flightOrderDto) {
        log.info("校验重复订单开始");
        PaymentRes res = new PaymentRes();
        FlightOrderReq req = new FlightOrderReq();
        for (PaxDto pax : flightOrderDto.getPaxs()) {
            req.setPassNo(pax.getPassNo());
            req.setFirstName(pax.getPassengerFirstName());
            req.setLastName(pax.getPassengerLastName());
            List<String> arrAirCds = new ArrayList<String>();
            List<String> depAirCds = new ArrayList<String>();
            List<String> depTimes = new ArrayList<String>();
            List<String> depDates = new ArrayList<String>();
            List<String> flightNos = new ArrayList<String>();
            for (SegmentDto segment : pax.getSegments()) {
                arrAirCds.add(segment.getArrAirpCd());
                depAirCds.add(segment.getDepAirpCd());
                depTimes.add(segment.getDepTm());
                depDates.add(new SimpleDateFormat("yyyy-MM-dd").format(segment.getDepDt()));
                flightNos.add(segment.getFlightNo());
            }
            req.setArrAirCds(arrAirCds);
            req.setDepAirCds(depAirCds);
            req.setDepDates(depDates);
            req.setDepTimes(depTimes);
            req.setFlightNos(flightNos);
            long begin = System.currentTimeMillis();
            List<FlightOrderDto> flightOrderDtos = flightOrderService.getFlightOrdersByFlightOrderReq(req);
            log.info("重复订单查询飞机订单数量" + flightOrderDtos.size());
            log.debug("重复订单查询数据" + JSONObject.toJSONString(flightOrderDtos));
            long end = System.currentTimeMillis();
            log.info("查询用时" + (end - begin));
            for (FlightOrderDto flightOrderDto2 : flightOrderDtos) {
                if (flightOrderDto2.getFlightOrderNo().equals(flightOrderDto.getFlightOrderNo())) {
                	List<PaxDto> paxs = flightOrderDto2.getPaxs();
                	for (PaxDto paxDto : paxs) {
                		if(paxDto.getModifySt() == 3 || paxDto.getModifySt() == 4) {
                			flightOrderDtos.remove(flightOrderDto2);
                		}
                	}
                    break;
                }
            }
            if (flightOrderDtos == null || flightOrderDtos.size() == 0) {
                continue;
            }
            for (FlightOrderDto flightOrderDto1 : flightOrderDtos) {
                if (flightOrderDto1.getOrderSt() == 2 || flightOrderDto1.getOrderSt() == 3 || flightOrderDto1.getOrderSt() == 4 || flightOrderDto1.getOrderSt() == 8) {//针对有效且支付完成订单
                    List<SegmentDto> sameSegs = new ArrayList<SegmentDto>();//相同的航段
                    List<SegmentDto> segments = new ArrayList<SegmentDto>();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    for (PaxDto paxDto : flightOrderDto1.getPaxs()) {
                        if (paxDto.getModifySt() == 1 || paxDto.getModifySt() == 2 || paxDto.getModifySt() == 6) {//订单具有有效支付信息，人的状态为待开票，已开票，已挂起
                            segments = paxDto.getSegments();
                            break;
                        }
                    }
                    for (SegmentDto segmentDto : segments) {
                        for (SegmentDto segment : pax.getSegments()) {
                            //出发时间加出发到达机场的字符串
                            if ((format.format(segmentDto.getDepDt()) + segmentDto.getDepTm() + segmentDto.getDepAirpCd() + segmentDto.getArrAirpCd()).equals(format.format(segment.getDepDt()) + segment.getDepTm() + segment.getDepAirpCd() + segment.getArrAirpCd())) {
                                sameSegs.add(segmentDto);
                            }
                        }
                    }
                    //已有订单航段全部包含现在选择的航段
                    if (sameSegs.size() == pax.getSegments().size()) {
                        if (flightOrderDto1.getOrderSt() == 1) {
                            res.setCode("10001");
                            res.setOrderNo(flightOrderDto1.getOrderNo());
                        } else if (flightOrderDto1.getOrderSt() == 2 || flightOrderDto1.getOrderSt() == 4 || flightOrderDto1.getOrderSt() == 8) {
                            res.setCode("10002");
                            res.setOrderNo(flightOrderDto1.getOrderNo());
                        } else if (flightOrderDto1.getOrderSt() == 3) {
                            res.setCode("10003");
                            res.setOrderNo(flightOrderDto1.getOrderNo());
                        } else if (flightOrderDto1.getOrderSt() == 7) {
                            boolean flag = false;
                            for (SegmentDto segmentDto : sameSegs) {
                                if (segmentDto.getTktID() != null && segmentDto.getTktID() != 0 && "OPEN_FOR_USE".equalsIgnoreCase(segmentDto.getSegSt())) {
                                    flag = true;
                                }
                            }
                            if (flag) {
                                res.setCode("10004");
                                res.setOrderNo(flightOrderDto1.getOrderNo());
                            }

                        }
                    } else if (sameSegs.size() != 0 && sameSegs.size() < pax.getSegments().size()) {
                        //部分包含
                        if (flightOrderDto1.getOrderSt() == 1) {
                            //验证支付时效有没有过
                            long createTime = flightOrderDto1.getCreateDtm().getTime();
                            long now = new Date().getTime();
                            if (now - createTime > 60 * 60 * 1000) {
                                return res;
                            } else {
                                res.setCode("10005");
                                res.setOrderNo(flightOrderDto1.getOrderNo());
                            }
                        } else if (flightOrderDto1.getOrderSt() == 8) {
                            res.setCode("10006");
                            res.setOrderNo(flightOrderDto1.getOrderNo());
                        } else if (flightOrderDto1.getOrderSt() == 2) {
                            res.setCode("10007");
                            res.setOrderNo(flightOrderDto1.getOrderNo());
                        } else if (flightOrderDto1.getOrderSt() == 3) {
                            res.setCode("10008");
                            res.setOrderNo(flightOrderDto1.getOrderNo());
                        } else if (flightOrderDto1.getOrderSt() == 7) {
                            boolean flag = false;
                            for (SegmentDto segmentDto : sameSegs) {
                                if (segmentDto.getTktID() != null && segmentDto.getTktID() != 0 && "OPEN_FOR_USE".equalsIgnoreCase(segmentDto.getSegSt())) {
                                    flag = true;
                                }
                            }
                            if (flag) {
                                res.setCode("10009");
                                res.setOrderNo(flightOrderDto1.getOrderNo());
                            }

                        }
                    }

                }
            }
        }
        return res;
    }

    @Source(name = "100310011002")
    @RequestMapping(value = "/sync/{site}", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public void syncPaymentCallback(HttpServletRequest request, HttpServletResponse response, @PathVariable String site) throws IOException {
        log.info("支付同步回调--------------开始！");
        StringBuffer url = request.getRequestURL();
        log.info("支付同步地址：------------" + url + "-----------------");
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
        //统一支付同步回调地址切换https站点的配置
        String syncUrlSite = uniConfigManagerWS.findSiteInfo2ByChannel(111111L).getUniconfigVO().getAsyncUrlSite();
        if(StringUtils.isNotEmpty(syncUrlSite) && syncUrlSite.contains(site)){
        	tempContextUrl = tempContextUrl.replace("http","https");
        }
        log.info("支付同步地址 tempContextUrl：------------" + tempContextUrl + "-----------------");
        String clientIps = HttpUtils.getIpAddr(request);
        String lang = site.substring(0, 2);
        log.info(KafkaLayout.format(null, null, null, null, clientIps, "统一支付同步回调开始，开始时间：" + System.currentTimeMillis()));

        StringBuffer strBuffer = new StringBuffer();
        strBuffer.append("<root><Details><Detail>");
        Map<String, String[]> paraMap = request.getParameterMap();
        Set<String> keys = paraMap.keySet();
        for (Iterator<String> itt = keys.iterator(); itt.hasNext();) {
            String key = itt.next();
            String[] value = (String[]) paraMap.get(key);
            strBuffer.append("<").append(key).append(">").append(value[0]).append("</").append(key).append(">");
        }
        /*String xmlTemp = strBuffer.toString();
		int index = xmlTemp.indexOf(">") + 1;*/
        strBuffer.append("</Detail></Details></root>");
        //String temp1 = "<root><Details><Detail>" + xmlTemp.substring(index) + "</Detail></Details></root>";
        String temp1 = strBuffer.toString();
        log.info("支付同步回调--------------参数：" + temp1);
        PayResponseDto payResp = XmlToDtoUtils.XmltoDto(temp1);

        SyncPaymentCallbackDto paySyncDto = paymentService.syncPaymentCallback(request.getCharacterEncoding(), payResp);
        log.info(KafkaLayout.format(null, null, null, null, clientIps, "统一支付同步回调结束，结束时间：" + System.currentTimeMillis()));
        log.info("支付同步回调--------------结束！");
        Integer productType = 0;
        PayProductDto payDto = new PayProductDto();
        Set<PayProductDto> payProductDtolist = paySyncDto.getPayDto().getPayProducts();
        if (payProductDtolist.isEmpty()) {
            throw new ActionException(GlobalExceptionConstants.PAYMENT_00008);
        } else if (payProductDtolist.size() > 1) {
            //多产品在主流程支付以机票订单为主
            for (PayProductDto dto : payProductDtolist) {
                payDto = dto;
                productType = dto.getProductType();
                if (productType == 1) {
                    break;
                }
            }
        } else {
            for (PayProductDto dto : payProductDtolist) {
                payDto = dto;
                productType = dto.getProductType();
                break;
            }
        }
        log.info("支付产品类型==================" + productType + payDto.getProductId());
        String contactName = orderService.getOrderByOrderNo(payDto.getOrderNo()).getContactNm();
        if (productType == 1) {//机票订单
            if (payResp.getDetails().get(0) != null && (payResp.getDetails().get(0).getRespCode().equals("000000") || payResp.getDetails().get(0).getRespCode().equals("666666"))) {
                log.info("支付产品类型==机票==================orderNo：" + paySyncDto.getPayDto().getOrderNo());
                response.sendRedirect(tempContextUrl + "/" + lang + "/payment-result.html?orderNo=" + paySyncDto.getPayDto().getOrderNo()+"&flightOrderList="+payDto.getProductId()+"&productTypes=1&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/payment-result.html?orderNo="+paySyncDto.getLog().getOrderNo();
            } else {
                log.info("支付产品类型==机票失败==================orderNo：" + paySyncDto.getPayDto().getOrderNo());
                response.sendRedirect(tempContextUrl + "/" + lang + "/payment-result.html?orderNo=" + paySyncDto.getPayDto().getOrderNo() + "&paymentResult=N&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/payment-result.html?orderNo="+paySyncDto.getLog().getOrderNo()+"&paymentResult=N";
            }

        }
        if (productType == 2) {//emd选座订单
            String emdNos = new String();
            for (PayProductDto dto : paySyncDto.getPayDto().getPayProducts()) {
                emdNos = emdNos + dto.getProductId() + ",";
            }
            if (payResp.getDetails().get(0) != null && (payResp.getDetails().get(0).getRespCode().equals("000000") || payResp.getDetails().get(0).getRespCode().equals("666666"))) {
                log.info("支付产品类型==选座==================emdNos：" + emdNos.substring(0, emdNos.length() - 1));
                response.sendRedirect(tempContextUrl + "/" + lang + "/paymentseat-result.html?paied=Y&emdNos" + emdNos.substring(0, emdNos.length() - 1)+"&productTypes=2&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/paymentseat-result.html?paied=Y&emdNos"+emdNos.substring(0, emdNos.length()-1);
            } else {
                log.info("支付产品类型==选座失败==================emdNos：" + emdNos.substring(0, emdNos.length() - 1));
                response.sendRedirect(tempContextUrl + "/" + lang + "/paymentseat-result.html?paied=Y&emdNos" + emdNos.substring(0, emdNos.length() - 1) + "&paymentResult=N&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/paymentseat-result.html?paied=Y&emdNos"+emdNos.substring(0, emdNos.length()-1)+"&paymentResult=N";
            }

        }
        if (productType == 3) {//改期订单
            if (payResp.getDetails().get(0) != null && (payResp.getDetails().get(0).getRespCode().equals("000000") || payResp.getDetails().get(0).getRespCode().equals("666666"))) {
                log.info("支付产品类型==改期==================flightOrderNo：" + payDto.getProductId());
                response.sendRedirect(tempContextUrl + "/" + lang + "/reschedule-result.html?flightOrderNo=" + payDto.getProductId()+"&productTypes=3&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/reschedule-result.html?flightOrderNo="+payDto.getProductId();
            } else {
                log.info("支付产品类型==改期失败==================flightOrderNo：" + payDto.getProductId());
                response.sendRedirect(tempContextUrl + "/" + lang + "/reschedule-result.html?flightOrderNo=" + payDto.getProductId() + "&paymentResult=N&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/reschedule-result.html?flightOrderNo="+payDto.getProductId()+"&paymentResult=N";
            }
        }
        if (productType == 5) {//愈重行李
            String bagNos = new String();
            for (PayProductDto dto : paySyncDto.getPayDto().getPayProducts()) {
                bagNos = bagNos + dto.getProductId() + ",";
            }
            if (payResp.getDetails().get(0) != null && (payResp.getDetails().get(0).getRespCode().equals("000000") || payResp.getDetails().get(0).getRespCode().equals("666666"))) {
                log.info("支付产品类型==愈重行李==================bagNos：" + bagNos.substring(0, bagNos.length() - 1));
                response.sendRedirect(tempContextUrl + "/" + lang + "/paymentbaggage-result.html?paied=Y&baggageNos=" + bagNos.substring(0, bagNos.length() - 1)+"&productTypes=5&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/paymentseat-result.html?paied=Y&emdNos"+emdNos.substring(0, emdNos.length()-1);
            } else {
                log.info("支付产品类型==愈重行李失败==================bagNos：" + bagNos.substring(0, bagNos.length() - 1));
                response.sendRedirect(tempContextUrl + "/" + lang + "/paymentbaggage-result.html?paied=Y&baggageNos=" + bagNos.substring(0, bagNos.length() - 1) + "&paymentResult=N&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/paymentseat-result.html?paied=Y&emdNos"+emdNos.substring(0, emdNos.length()-1)+"&paymentResult=N";
            }
        }
        if (productType == 7) {//高铁（单独购买）
            String gaotieNos = new String();
            for (PayProductDto dto : paySyncDto.getPayDto().getPayProducts()) {
            	gaotieNos = gaotieNos + dto.getProductId() + ",";
            }
            if (payResp.getDetails().get(0) != null && (payResp.getDetails().get(0).getRespCode().equals("000000") || payResp.getDetails().get(0).getRespCode().equals("666666"))) {
                log.info("支付产品类型==高铁==================gaotieNos：" + gaotieNos.substring(0, gaotieNos.length() - 1));
                response.sendRedirect(tempContextUrl + "/" + lang + "/payment-result.html?orderNo="+ paySyncDto.getPayDto().getOrderNo()+"&gaotieList=" + gaotieNos.substring(0, gaotieNos.length() - 1)+"&productTypes=7&contactName=" + contactName);
            } else {
                log.info("支付产品类型==高铁失败==================gaotieNos：" + gaotieNos.substring(0, gaotieNos.length() - 1));
                response.sendRedirect(tempContextUrl + "/" + lang + "/payment-result.html?orderNo="+ paySyncDto.getPayDto().getOrderNo()+"&gaotieList=" + gaotieNos.substring(0, gaotieNos.length() - 1) + "&paymentResult=N&contactName=" + contactName);
            }
        }
        if (productType == 11) {//购买积分
            if (payResp.getDetails().get(0) != null && (payResp.getDetails().get(0).getRespCode().equals("000000") || payResp.getDetails().get(0).getRespCode().equals("666666"))) {
                log.info("支付产品类型==购买积分==================orderNo：" + paySyncDto.getPayDto().getOrderNo());
                response.sendRedirect(tempContextUrl + "/" + lang + "/payment-result.html?orderNo="+ paySyncDto.getPayDto().getOrderNo()+"&productTypes=11&contactName=" + contactName);
            } else {
                log.info("支付产品类型==购买积分失败==================orderNo：" + paySyncDto.getPayDto().getOrderNo());
                response.sendRedirect(tempContextUrl + "/" + lang + "/payment-result.html?orderNo="+ paySyncDto.getPayDto().getOrderNo()+"&paymentResult=N&contactName=" + contactName);
            }
        }
        if (productType == 12) {//升舱订单
            if (payResp.getDetails().get(0) != null && (payResp.getDetails().get(0).getRespCode().equals("000000") || payResp.getDetails().get(0).getRespCode().equals("666666"))) {
                log.info("支付产品类型==升舱==================flightOrderNo：" + payDto.getProductId());
                response.sendRedirect(tempContextUrl + "/" + lang + "/payment-result.html?flightOrderList=" + payDto.getProductId()+"&orderNo="+paySyncDto.getPayDto().getOrderNo()+"&productTypes=12&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/reschedule-result.html?flightOrderNo="+payDto.getProductId();
            } else {
                log.info("支付产品类型==升舱失败==================flightOrderNo：" + payDto.getProductId());
                response.sendRedirect(tempContextUrl + "/" + lang + "/payment-result.html?flightOrderList=" + payDto.getProductId()+"&orderNo="+paySyncDto.getPayDto().getOrderNo()+"&paymentResult=N&contactName=" + contactName);
                //return "redirect:"+tempContextUrl+"/"+lang+"/reschedule-result.html?flightOrderNo="+payDto.getProductId()+"&paymentResult=N";
            }
        }
        /*if(productType == 4){//vip订单
			redirectAttributes.addFlashAttribute("flightOrderNo", payResp);
			return "redirect:"+lang+"/reschedule-result.html";
		}
		if(productType == 8){//其他非航订单
			redirectAttributes.addFlashAttribute("flightOrderNo", payResp);
			return "redirect:"+lang+"/reschedule-result.html";
		}*/
        //redirectAttributes.addFlashAttribute("orderNo", paySyncDto.getLog().getOrderNo());
        response.sendRedirect(tempContextUrl + "/" + lang + "/payment-result.html?orderNo=" + paySyncDto.getPayDto().getOrderNo());
        //return "redirect:"+tempContextUrl+"/"+lang+"/payment-result.html?orderNo="+paySyncDto.getLog().getOrderNo();
    }

    @Source(name = "100310011003")
    @RequestMapping(value = "/async", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String asyncPaymentCallback(HttpServletRequest request) {
    	try {
	        log.info("支付异步回调--------------开始！");
	        String clientIps = HttpUtils.getIpAddr(request);
	        log.info(KafkaLayout.format(null, null, null, null, clientIps, "统一支付异步回调开始，开始时间：" + System.currentTimeMillis()));
	        StringBuffer strBuffer = new StringBuffer();
	        Map<String, String[]> paraMap = request.getParameterMap();
	        Set<String> keys = paraMap.keySet();
	        for (Iterator<String> itt = keys.iterator(); itt.hasNext();) {
	            String key = itt.next();
	            String[] value = (String[]) paraMap.get(key);
	            strBuffer.append(key).append("=").append(value[0]);
	        }
	        String xmlTemp = strBuffer.toString();
	        int index = xmlTemp.indexOf(">") + 1;
	        /*
			 * String temp1 = xmlTemp.substring(index).replace("<Details>",
			 * "<root>").replace("</Details>", "</root>");
	         */
	        String temp1 = "<root>" + xmlTemp.substring(index) + "</root>";
	        log.info("支付异步回调--------------参数：" + temp1);
	        PayResponseDto payResp = XmlToDtoUtils.XmltoDto(temp1);
	        paymentService.asyncPaymentCallback(request.getCharacterEncoding(), payResp);
	        log.info(KafkaLayout.format(null, null, null, null, clientIps, "统一支付异步回调结束，结束时间：" + System.currentTimeMillis()));
	        log.info("支付异步回调--------------结束！");
	        return "RECV_ORD_ID_" + payResp.getDetails().get(0).getSysSeqId();
    	}catch(Exception e) {
    		log.info("支付异步回调异常:",e);
    		return null;
    	}
    }

    @Source(name = "100310011004")
    @RequestMapping(value = "/getFlightOrderDetial", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getFlightOrderDetail(HttpServletRequest request, @RequestParam String orderNo) {
        String clientIps = null;
    	try {
    		UniFndConfigRS cfg = uniConfigManagerWS.findUniFndConfigByCode("UNI_PAY_SUSPEND_IP");
        	String ip = cfg.getUniFndConfigVO().getCfgValue();
        	clientIps = HttpUtils.getIpAddr(request);
        	if(!ip.contains(clientIps)){
        		log.error(ip+"ip不合法");
        		return null;
        	}
		} catch (Exception e) {
			log.error("ticketSuspendAndResume异常",e);
		}
        log.info(KafkaLayout.format(null, null, null, null, clientIps, "统一支付获取机票订单信息开始，开始时间：" + System.currentTimeMillis()));
        String value = XmlToDtoUtils.DtotoXml(paymentService.findFlightOrderList(orderNo));
        log.info(KafkaLayout.format(null, null, null, null, clientIps, "统一支付获取机票订单信息结束，结束时间：" + System.currentTimeMillis()));
        return value;
    }
    
    @RequestMapping(value = "/getEmdOrderDetial", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getEmdOrderDetail(HttpServletRequest request, @RequestParam String emdOrderNo) {
        String clientIps = HttpUtils.getIpAddr(request);
        log.info(KafkaLayout.format(null, null, null, null, clientIps, "统一支付获取emd订单信息开始，开始时间：" + System.currentTimeMillis()));
        String value = paymentService.findEmdOrder(emdOrderNo);
        log.info(KafkaLayout.format(null, null, null, null, clientIps, "统一支付获取emd订单信息结束，结束时间：" + System.currentTimeMillis()));
        return value;
    }

    public static void main(String[] args) {
        String msg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Details><Detail><CmdId>PAYORD</CmdId><RespCode>000000</RespCode><ErrorDesc></ErrorDesc><SCCode>B2BSC1003</SCCode><SubSCCode>SUBB2BSC1001</SubSCCode><PCCode>CC003T</PCCode><SubPCCode>SUBPNR002T</SubPCCode><SCOrdId>tki1tsm03</SCOrdId><SCAcctDate>20160629</SCAcctDate><SysSeqId>2016062900346983</SysSeqId><AcctDate>20160629</AcctDate><SysTime>153017</SysTime><ActualPayAmt>252.00</ActualPayAmt><CurCode>CNY</CurCode><BankCode> </BankCode><PCSysSeqId></PCSysSeqId><PCAcctDate>20160629</PCAcctDate><Resv1></Resv1><Resv2></Resv2><Resv3></Resv3><Resv4></Resv4><Resv5></Resv5><Resv6></Resv6><SignType>MD5</SignType><SignValue>4AB304DC45B8197E963038FFE940F76E</SignValue></Detail></Details>";
        int index = msg.indexOf(">");
        String temp1 = msg.substring(index + 1).replace("<Details>", "<root>").replace("</Details>", "</root>");
        System.out.println(temp1);
        String site = "en_US";
        String transWebCountryCode = site.substring(site.length() - 2);
        System.out.println(transWebCountryCode);

        Date start = new Date();
        SimpleDateFormat ssf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(ssf.format(start));
        for (int i = 0; i < 1000000; i++) {
            System.out.print("-");
        }
        System.out.println("-");
        Date end = new Date();
        SimpleDateFormat esf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(esf.format(end));

        System.out.println((end.getTime() - start.getTime()) + "毫秒");

    }

    @Source(name = "100310011005")
    @RequestMapping(value = "/paysuccess", method = RequestMethod.GET)
    @ResponseBody
    public PayStatusVO getPayStatus(HttpServletRequest request, @RequestParam String orderNo, @RequestParam(required = false) String[] emdOrderNos, @RequestParam(required = false) String flightOrderNo, @CookieValue(value = "inter", defaultValue = "en_US") String site, @CookieValue(value = "global_site_flag", defaultValue = "") String nsite) {
        log.info("nsite=" + nsite + "----------------site=" + site);
        if (null != nsite && !"".equals(nsite)) {
            site = nsite;
        }
        log.info("查询开始");
        PayStatusVO payVO = paymentService.getPayStatus(orderNo, emdOrderNos, flightOrderNo);
        log.info("查询结束");
        return payVO;
    }

    @Source(name = "100310011006")
    @RequestMapping(value = "/getPaymentBaseParam", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getPaymentBaseParam(HttpServletRequest request, @RequestParam(required = false) String scCode,
            @RequestParam(required = false) String subScCode, @RequestParam(required = false) String ceairMember,
            @RequestParam(required = false) String amount) {
        Map<String, Object> payBaseParam = new HashMap<String, Object>();
        try {
            String productOrderNo = request.getParameter("productOrderNo");
            if (null != productOrderNo && !"".equals(productOrderNo)) {
                productOrderNo = productOrderNo.split(",")[0];
                BookingOrderMoreParam bparam = new BookingOrderMoreParam();
                if (productOrderNo.startsWith("11")) {
                    bparam.setFlightorderNo(productOrderNo);
                } else if (productOrderNo.startsWith("12")) {
                    bparam.setSeatorderNo(productOrderNo);
                } else if (productOrderNo.startsWith("15")) {
                    bparam.setBageorderNo(productOrderNo);
                } else if (productOrderNo.startsWith("17")) {
                    bparam.setGaotieorderNo(productOrderNo);
                } else if (productOrderNo.startsWith("16")) {
                    bparam.setViporderNo(productOrderNo);
                } else if (productOrderNo.startsWith("13")) {
                    bparam.setWifiorderNo(productOrderNo);
                } else if (productOrderNo.startsWith("22")) {
                    bparam.setPurchasePointsOrderNo(productOrderNo);
                }

                List<BookingOrderDto> bookingOrderDtoList = flightOrderService.getBookingOrderDtoListByMoreParam(bparam);
                if (null != bookingOrderDtoList && bookingOrderDtoList.size() > 0) {
                    BookingOrderDto bookingOrderDto = bookingOrderDtoList.get(0);
                    try {
                    		Long createTime = bookingOrderDto.getCreateDtm().getTime();
                    		Date date = new Date();
                    		//获取支付倒计时
                    		log.info("--调用公共服务获取支付倒计时开始:" + bookingOrderDto.getChannel());
                    		UniConfigRS uniConfigRS = uniConfigManagerWS.findSiteInfo2ByChannel(Long.parseLong(bookingOrderDto.getChannel()));
                    		Long comeLeaveTime = uniConfigRS.getUniconfigVO().getCtdTime();
                    		log.info("--调用公共服务获取支付倒计时结束:" + comeLeaveTime);
                    		if (productOrderNo.startsWith("12")) {
	                        	SeatParam param = new SeatParam();
	                			param.setBookingOrderNo(bookingOrderDto.getBookingOrderNo());
	                			List<SeatDto> seatDtoList = emdOrderService.getSeatDtoListByParam(param);
	                			for (SeatDto seatDto : seatDtoList) {
	                				if(seatDto.getCreateDtm().getTime() < createTime) {
	                					createTime = seatDto.getCreateDtm().getTime();
	                				}
	                			}
                        		comeLeaveTime = 25 * 60 * 1000l;
                        		log.info("--选座倒计时时间取选座订单的创建时间:" + createTime);
                    		}
                    		if (productOrderNo.startsWith("15")){//MUIBTOC-5833
                    			comeLeaveTime = 30 * 60 * 1000l;
                        		log.info("--逾重行李订单倒计时上限时间改30分钟:" + comeLeaveTime);
                    		}
                        String channel = bookingOrderDto.getChannel();
                        String site = bookingOrderDto.getSite();
                        UniPayRS rs = uniConfigManagerWS.findPayInfoByChannel(Long.parseLong(channel));
                        List<Map<String, Object>> payTypeList = rs == null ? null : rs.getPayMapList();

                        List<PayDO> payDOList = payQueryService.getPayDOListByIndistinctProductNo(productOrderNo);
                        if (null != payDOList && payDOList.size() > 0) {
                            for (PayDO payDO : payDOList) {
                                if ("JPCVS".equals(payDO.getPccode())) {
                                    log.info("此订单订单已进行过便利店支付：" + productOrderNo);
                                    comeLeaveTime = 86400000L;
                                    payTypeList.clear();
                                    Map<String, Object> payTypeMap = new HashMap<String, Object>();
                                    payTypeMap.put("v", "jpcvus");
                                    payTypeMap.put("s", new ArrayList<Map<String, String>>());
                                    payTypeList.add(payTypeMap);
                                    break;
                                }
                            }
                        }
                        
                        List<Map<String, Object>> promoPayTypeList = paymentService.getPromoPayTypeList(productOrderNo);
                        if (null != promoPayTypeList) {
                            payTypeList = promoPayTypeList;
                        }
                        
                        //jira 3426
                        if(StringUtils.isNotEmpty(bookingOrderDto.getFlightOrderNo())){
                        	FlightOrderDto flightOrder = flightOrderService.getFlightOrderByFlightOrderNo(bookingOrderDto.getFlightOrderNo());
                        	if(flightOrder!=null){
                        		String beginDate = getDepDate(flightOrder);
                        		if(isLessThanDays(beginDate, 1) && isCabins(flightOrder,"UFPAJCDIO")){
                        			comeLeaveTime = 30 * 60 * 1000l;
                        		}
                        		//Jira MUIBTOC-2905
                        		removeJpcvs(flightOrder, payTypeList,amount);
                        	}
                        }
                                                
                        //jira 3129
                        removeEmd(bookingOrderDto.getSeatOrderNo(), payTypeList);
                        String jsessionid = request.getSession().getId();
                        Long time = date.getTime() - createTime;
                        log.info("--当前时间:" + date.getTime());
                        log.info("--订单时间:" + createTime);
                        
                        //如果台湾积分购票不显示国泰世华支付方式
                        //jira 4071 先注解掉
//                        if(bookingOrderDto.getTotalPoint()!=null&&site.contains("TW")&&new BigDecimal(0).compareTo(bookingOrderDto.getTotalPoint())==-1){
//                        	removeTWEPOS(payTypeList);
//                        }
                        
                        //jira 4476
                        if(site.contains("TW")){
                        	onlyTWEPOS(bookingOrderDto.getFlightOrderNo(), payTypeList);                        	
                        }
                        
                        payBaseParam.put("leaveTime", comeLeaveTime - time);
                        payBaseParam.put("jsessionid", jsessionid);
                        payBaseParam.put("site", site);
                        payBaseParam.put("paychannels", payTypeList);
                    } catch (Exception e) {
                        log.error("获取支付基础配置错误", e);
                    }

                }
            }
        } catch (Exception e) {
            log.error("获取支付渠道itching", e);
        }
//        try {
//            log.info("获取常用卡信息：" + scCode + "|" + subScCode + "|" + ceairMember);
//            if (StringUtils.isNotEmpty(scCode) && StringUtils.isNotEmpty(subScCode) && StringUtils.isNotEmpty(ceairMember)) {
//                CommonCardInfoRespDto commonCardInfoRespDto = paymentService.queryCardList(scCode, subScCode, ceairMember);
//                if ("00".equals(commonCardInfoRespDto.getRspCode()) && commonCardInfoRespDto.getRspMsg() != null) {
//                    payBaseParam.put("rspMsg", commonCardInfoRespDto.getRspMsg());
//                    payBaseParam.put("rspMsgs", commonCardInfoRespDto.getRspMsgs());
//                }
//            }
//        } catch (Exception e) {
//            log.error("获取常用卡信息错误", e);
//        }
        return payBaseParam;
    }

    private void removeJpcvs(FlightOrderDto flightOrder, List<Map<String, Object>> promoPayTypeList, String amount) {
        try {
        	if (promoPayTypeList != null && flightOrder != null) {
        		Iterator<Map<String, Object>> iterMap = promoPayTypeList.iterator();
        		while (iterMap.hasNext()) {
        			Map<String, Object> payMethod = iterMap.next();
        			if (payMethod.containsValue("jpcvs") || payMethod.containsValue("JPCVS")) {
        				String beginDate = getDepDate(flightOrder);
        				Long price = 0l;
        				try {
        					price = StringUtils.isEmpty(amount)?0:Long.parseLong(amount);
        				} catch (Exception e) {
        					price = 0l;
        				}
        				log.info("jpcvs payment info:"+flightOrder.getFlightOrderNo()+","+beginDate+","+amount);
        				boolean isInValidForJpcvs = isCabins(flightOrder,"VT") || isLessThanDays(beginDate, 3) || (price>300000);
        				if (isInValidForJpcvs) {
        					iterMap.remove();
        					break;
        				}
        			}
        		}
        	}
        } catch (Exception ex) {
            log.error("Checked jpcvs payment error", ex);
        }
    }
    
    private boolean isCabins(FlightOrderDto flightOrder,String cabins){
    	List<SegmentDto> segs = flightOrder.getPaxs().get(0).getSegments();
    	for (SegmentDto seg : segs) {
    		String cabin = seg.getClassTp();
    		if(cabins.contains(cabin.toUpperCase())){
    			return true;
    		}
    	}
    	return false;
    }

    private String getDepDate(FlightOrderDto flightOrder) {
        List<SegmentDto> segs = flightOrder.getPaxs().get(0).getSegments();
        SegmentDto seg = segs.get(0);//assume the first segment is the begin segment
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");        
        return  df.format(seg.getDepDt())+ " " + seg.getDepTm();
    }

    /**
     *
     * date yyyy-MM-dd HH:mm
     */
    private boolean isLessThanDays(String dateStr, int days) {
        if (dateStr == null) {
            return false;
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        try {
            Date date = df.parse(dateStr);
            Date now = new Date();
            if (date.getTime() - (days * 24 * 60 * 60 * 1000) <= now.getTime()) {
                return true;
            }
        } catch (ParseException ex) {
            log.error("Parse date error" + dateStr, ex);
        }
        return false;
    }
    
    private void removeEmd(String seatOrderNo, List<Map<String, Object>> promoPayTypeList) {
    	try {
    		if(promoPayTypeList != null && seatOrderNo != null && !"".equals(seatOrderNo)){
    			Iterator<Map<String, Object>> iterMap = promoPayTypeList.iterator();
    			while (iterMap.hasNext()) {
    				Map<String, Object> payMethod = iterMap.next();
    				if (payMethod.containsValue("jpcvs") || payMethod.containsValue("jpips") 
    				|| payMethod.containsValue("lgu") || payMethod.containsValue("uatp")
    				|| payMethod.containsValue("twepos")) {
						iterMap.remove();
    				}
    			}
    		}			
		} catch (Exception e) {
			log.error("Checked emd payment error", e);
		}
    }
//    private void removeTWEPOS(List<Map<String, Object>> promoPayTypeList) {
//    	try {
//    		Iterator<Map<String, Object>> iterMap = promoPayTypeList.iterator();
//			while (iterMap.hasNext()) {
//				Map<String, Object> payMethod = iterMap.next();
//				if (payMethod.containsValue("twepos")) {
//					iterMap.remove();
//				}
//			}
//		} catch (Exception e) {
//			log.error("point pay remove twepos error", e);
//		}
//    }
    private void onlyTWEPOS(String flightOrderNo, List<Map<String, Object>> promoPayTypeList) {
    	log.info("台湾促销支付必须国泰世华开始："+flightOrderNo);
    	try {
    		if(promoPayTypeList != null && StringUtils.isNotEmpty(flightOrderNo)){
    			FlightOrderDto flightOrderDto = flightOrderService.getFlightOrderDto(flightOrderNo);
    			String promoCode = flightOrderDto.getPromoCode();
    			log.info("台湾促销支付必须国泰世华促销码："+promoCode);
    			if(flightOrderDto != null && StringUtils.isNotEmpty(promoCode)){
        			String SUBTWEPOS007 = uniConfigManagerWS.findSiteInfo2ByChannel(10190007L).getUniconfigVO().getBankCodePromo();
        			String SUBTWEPOS008 = uniConfigManagerWS.findSiteInfo2ByChannel(10190008L).getUniconfigVO().getBankCodePromo();
        			String SUBTWEPOS012 = uniConfigManagerWS.findSiteInfo2ByChannel(10190012L).getUniconfigVO().getBankCodePromo();
        			String SUBTWEPOS015 = uniConfigManagerWS.findSiteInfo2ByChannel(10190015L).getUniconfigVO().getBankCodePromo();
        			String SUBTWEPOS016 = uniConfigManagerWS.findSiteInfo2ByChannel(10190016L).getUniconfigVO().getBankCodePromo();
        			String SUBTWEPOS022 = uniConfigManagerWS.findSiteInfo2ByChannel(10190022L).getUniconfigVO().getBankCodePromo();
        			if(SUBTWEPOS007.contains(promoCode) || SUBTWEPOS008.contains(promoCode) || SUBTWEPOS012.contains(promoCode)
        				|| SUBTWEPOS015.contains(promoCode) || SUBTWEPOS016.contains(promoCode) || SUBTWEPOS022.contains(promoCode)){
        				Iterator<Map<String, Object>> iterMap = promoPayTypeList.iterator();
        				while (iterMap.hasNext()) {
        					Map<String, Object> payMethod = iterMap.next();
        					if (payMethod.containsValue("jpcvs") || payMethod.containsValue("jpips") 
        							|| payMethod.containsValue("lgu") || payMethod.containsValue("uatp")
        							|| payMethod.containsValue("unionpay") || payMethod.containsValue("worldpay")) {
        						iterMap.remove();
        					}
        				}
        			}
    			}
    		}
		} catch (Exception e) {
			log.error("台湾促销支付必须国泰世华异常", e);
		}
    }

    @RequestMapping(value = "/ticketSuspendAndResume", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> ticketSuspendAndResume(HttpServletRequest request, @RequestParam String orderNo, @RequestParam boolean suspend) {
    	try {
    		UniFndConfigRS cfg = uniConfigManagerWS.findUniFndConfigByCode("UNI_PAY_SUSPEND_IP");
        	String ip = cfg.getUniFndConfigVO().getCfgValue();
        	String clientIps = HttpUtils.getIpAddr(request);
        	if(!ip.contains(clientIps)){
        		log.error(ip+"ip不合法");
        		return null;
        	}
		} catch (Exception e) {
			log.error("ticketSuspendAndResume异常",e);
		}
    	
    	//suspend true 挂起，false解挂
        List<Map<String, Object>> suspendAndResume = paymentService.suspendAndResume(orderNo, suspend);
        return suspendAndResume;
    }

    @RequestMapping(value = "/uploadIdCard", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject uploadIdCard(@RequestParam String sysSeqId,@RequestParam(value = "remainTime", required = false) String remainTime, @RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        JSONObject json = new JSONObject();
        String result = "";
        
        String uploadUrl = GlobalExceptionUtils.getStringValue("payment_uploadIdCard_upload");
        
        log.info("证件上传调用链接："+uploadUrl);
        String localTempPath = com.ceair.mub2c.payment.payments.utils.StringUtils.getRootPath() + File.separatorChar;
        String fileName = file.getOriginalFilename();
        log.info("文件地址："+localTempPath+"文件名:"+fileName);
        try {
        	
            // 服务器IP(这里是从属性文件中读取出来的)
            URL url = new URL(uploadUrl);

            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            // 上传图片的一些参数设置
            uc.setRequestProperty(
                    "Accept",
                    "image/gif,  image/png, image/jpeg, image/pjpeg, */*");
            uc.setRequestProperty("Accept-Language", "zh-cn");
            uc.setRequestProperty("Content-type",
                    "multipart/form-data;   boundary=---------------------------7d318fd100112");
            uc.setRequestProperty("Accept-Encoding", "gzip,   deflate");
            uc.setRequestProperty("User-Agent",
                    "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1)");
            uc.setRequestProperty("Connection", "Keep-Alive");
            uc.setDoOutput(true);
            uc.setUseCaches(true);
            log.info("开始写文件");
            File f = new File(localTempPath + fileName);
            file.transferTo(f);
            log.info("写文件完毕");
            // 读取文件流
            int size = (int) f.length();
            byte[] data = new byte[size];
            FileInputStream fis = new FileInputStream(f);
            OutputStream out = uc.getOutputStream();
            fis.read(data, 0, size);
            
            // 写入订单号
            out.write(sysSeqId.getBytes());
            // 写入分隔符
            out.write('|');
            // 写入文件名
            out.write(f.getName().trim().getBytes());
            // 写入分隔符
            out.write('|');
            // 写入图片流
            out.write(data);
            out.flush();
            out.close();
            fis.close();
            f.delete();
            log.info("参数传递完毕");
            // 读取响应数据
            int code = uc.getResponseCode();
            String sCurrentLine = "";
            // 存放响应结果
            String sTotalString = "";
            if (code == 200) {
                java.io.InputStream is = uc.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is,"utf-8"));
                while ((sCurrentLine = reader.readLine()) != null) {
                    if (sCurrentLine.length() > 0) {
                        sTotalString = sTotalString + sCurrentLine.trim();
                    }
                }
                result = sTotalString;
                json.put("flag", true);
                json.put("result", result);
                return json;
            } else {
                sTotalString = "远程服务器连接失败,错误代码:" + code;
                result = sTotalString;
                json.put("flag", false);
                json.put("result", result);
                return json;
            }

        } catch (Exception e) {
            json.put("flag", false);
            json.put("result", "程序异常:" + e.getMessage());
            return json;
        }

    }
    
    
    @RequestMapping(value = "/validate", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject validate(@RequestParam String sysSeqId){
    	JSONObject json = new JSONObject();
    	Boolean flag = false;
    	String leftTime = "";
    	try {
    	
    	String validateUrl = GlobalExceptionUtils.getStringValue("payment_uploadIdCard_validate");
        log.info("证件上传调用链接："+validateUrl);
    	
    	String sUrl = validateUrl+"?sysSeqId="+sysSeqId;
    	//http://172.31.69.47:8830/superRiskCoreservice/riskReview/validate.do?sysSeqId=2017112100481783&randomStr=1511249278471
		StringBuffer response = new StringBuffer();
		log.info("调用的校验了链接为："+sUrl);
		URL url = new URL(sUrl);
		HttpURLConnection huc = (HttpURLConnection) url.openConnection();

		String timeOutString = "10";

		huc.setReadTimeout(Integer.valueOf(timeOutString) * 1000);

		huc.setRequestMethod("GET");
		huc.setDoOutput(false);
		huc.setDoInput(true);
		huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; text/html; charset=utf-8");
		huc.setRequestProperty("Host", url.getHost());
		huc.setDoOutput(true);

		BufferedReader br = null;
		
			br = new BufferedReader(new InputStreamReader(huc.getInputStream(),"utf-8"));
			String line;
			while ((line = br.readLine()) != null) {
				response.append(line);
			}
			String rsp = response.toString();
			log.info("接收应答消息: " + rsp);
			//System.out.println(rsp);
			
			com.alibaba.fastjson.JSONObject resJson= (com.alibaba.fastjson.JSONObject)  com.alibaba.fastjson.JSON.parse(rsp);
			String resFlag = (String)resJson.get("flag");
			if(StringUtils.isNoneEmpty(resFlag)){
				if("1".equals(resFlag)){//校验通过
					leftTime = (String)resJson.get("remainTime");
					json.put("leftTime", leftTime);
					json.put("errorInfo", "");
					flag = true;
				}else{
					leftTime = (String)resJson.get("remainTime");
					json.put("errorInfo", leftTime);
				}
			}else{
				json.put("errorInfo", "风控校验不通过");
			}
			json.put("flag", flag);
			return json;
			
		} catch (Exception e) {
			log.error("上传证件校验异常:"+e.getMessage());
			json.put("flag", false);
			json.put("errorInfo", e.getMessage());
			json.put("leftTime", leftTime);
			return json;
		}
    }
    
    @RequestMapping(value = "/modifyPayType", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> modifyPayType(@RequestBody PayTypeRq payTypeRq/*, HttpServletRequest request,
			HttpServletResponse response*/){
    	Map<String,Object> map = new HashMap<String,Object>();
    	log.info("进去modifyPayType方法");
//    	String ip = DataUtils.toString(HttpUtils.getIpAddr(request)); // 获取请求端的ip地址
    	//判断IP地址 测试环境172.31.65./172.28.33.
    	/*if(ip!=null && !"".equals(ip)){
    		if(!(ip.startsWith("172.31.65.") || ip.startsWith("172.28.33."))){
    			map.put("success", false);
    			map.put("msg", "ip地址异常，不属于生产和测试环境ip");
    			return map;
        	}
    	}*/
//    	UserInfoBean sessionUser = UserContext.getUser(request);// 获取当前session用户信息
//    	String sessionUserId = DataUtils.toString(sessionUser.getCustomerid()); // 获取用户id
//    	payTypeRq.setOptID(sessionUserId);
    	payTypeRq.setOptID("guest");
    	payTypeRq.setOptDT(new Date());
    	map = paymentService.modifyPayType(payTypeRq);
    	uniConfigManagerWS.refreshConfigDataCache();
    	return map;
    }
    
    @RequestMapping(value = "/deletePayType", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> deletePayType(@RequestBody PayTypeRq payTypeRq/*, HttpServletRequest request,
			HttpServletResponse response*/){
    	Map<String,Object> map = new HashMap<String,Object>();
    	log.info("进去deletePayType方法");
//    	String ip = DataUtils.toString(HttpUtils.getIpAddr(request)); // 获取请求端的ip地址
    	//判断IP地址 测试环境172.31.65./172.28.33.
    	/*if(ip!=null && !"".equals(ip)){
    		if(!(ip.startsWith("172.31.65.") || ip.startsWith("172.28.33."))){
    			map.put("success", false);
    			map.put("msg", "ip地址异常，不属于生产和测试环境ip");
    			return map;
        	}
    	}*/
//    	UserInfoBean sessionUser = UserContext.getUser(request);// 获取当前session用户信息
//    	String sessionUserId = DataUtils.toString(sessionUser.getCustomerid()); // 获取用户id
//    	payTypeRq.setOptID(sessionUserId);
    	payTypeRq.setOptID("guest");
    	payTypeRq.setOptDT(new Date());
    	map = paymentService.deletePayType(payTypeRq);
    	uniConfigManagerWS.refreshConfigDataCache();
    	return map;
    }
    
    /**
	 * 刷新配置信息redis缓存
	 * 
	 */
	@RequestMapping(value="/refresh",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> refreshConfigDataCache(){
		Map<String,Object> map = new HashMap<String,Object>();
		BaseRS bs=uniConfigManagerWS.refreshConfigDataCache();
		if(bs.getMsgCode()==1){
			map.put("success", false);
			map.put("msg", "刷新失败");
			return map;
		}
		map.put("success", true);
		map.put("msg", "刷新成功");
		return map;
	}
}